package com.itestor.iptv.modules.ne.actions;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;

import com.itestor.iptv.global.actions.AbstractOFCDataAction;
import com.itestor.iptv.global.bean.OFCGraph;
import com.itestor.iptv.modules.ne.service.IptvQualityService;
import com.itestor.iptv.modules.ne.vo.IptvLostRateBean;
import com.itestor.iptv.modules.ne.vo.IptvQualityRateBean;
import com.itestor.iptv.modules.ne.vo.PictureData;

public class ServiceAvailabilityOFCDataAction extends AbstractOFCDataAction {
    /**
     * 
     */
    private Logger logger = Logger
            .getLogger(ServiceAvailabilityOFCDataAction.class);

    /**
     * iptvLostRateService
     */
    private IptvQualityService iptvQualityService;
    private Integer maxNum = 1;
    /**
     * 日期输入格式.
     */
    private final DateFormat DATE_FAMAT = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm", Locale.UK);

    /**
     * 日期输入格式.
     */
    private final DateFormat INPUT_FAMAT = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss", Locale.UK);

    public ServiceAvailabilityOFCDataAction() {
        super(null);
    }

    /**
     * @param iptvQualityService
     */
    public void setIptvQualityService(IptvQualityService iptvQualityService) {
        this.iptvQualityService = iptvQualityService;
    }

    @Override
    public OFCGraph buildData(ActionForm form, HttpServletRequest request) {
        Map<String, List<String>> returnMap = new HashMap<String, List<String>>();
        Map<String, List<String>> returnDateMap = new HashMap<String, List<String>>();
        List<String> randomColorList = new ArrayList<String>();
        // List<Object[]> returnList = new ArrayList<Object[]>();
        List<IptvQualityRateBean> qualityRateBeanList = new ArrayList<IptvQualityRateBean>();

        logger.info("ids param  :  " + request.getParameter("ids"));

//        String[] p1 = request.getParameter("pa").split("_!_");
//
//        Map<String, String> valueMap = new HashMap<String, String>();
//        
//        for (String str : p1) {
//            valueMap.put(str.split("@")[0], str.split("@")[1]);
//        }
        
        String time = request.getParameter("time");
        String start_time = request.getParameter("startTime");
        String end_time = request.getParameter("endTime");

        logger.info("buildData param time :" +time +" start_time : "+ start_time + " end_time :" +end_time);
        
        
        String[] p_ids = request.getParameter("ids").split("_");        
//      Long startTime = 0L;
//      Long endTime = System.currentTimeMillis() / 1000L;
        Integer statunitsec = 900;

        if ("15min".equals(time)) {
            // startTime = (System.currentTimeMillis()-15L*60L*1000L)/1000L;
            // endTime = System.currentTimeMillis()/1000L;
            statunitsec = 900;

        }
        if ("30min".equals(time)) {
            // startTime = (System.currentTimeMillis()-30L*60L*1000L)/1000L;
            // endTime = System.currentTimeMillis()/1000L;
            statunitsec = 1800;

        }
        if ("2hour".equals(time)) {
            // startTime = (System.currentTimeMillis()-2L*60L*60L*1000L)/1000L;
            // endTime = System.currentTimeMillis()/1000L;
            statunitsec = 7200;
        }

        
        
        
        Calendar start_Calendar = Calendar.getInstance();
        start_Calendar.set(Calendar.DAY_OF_MONTH, start_Calendar
                .get(Calendar.DAY_OF_MONTH - 1));
        Date start = start_Calendar.getTime();

        Calendar end_Calendar = Calendar.getInstance();
        Date end = end_Calendar.getTime();

        if (!StringUtils.isEmpty(start_time)) {
            try {
                start = DATE_FAMAT.parse(start_time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (!StringUtils.isEmpty(end_time)) {
            try {
                end = DATE_FAMAT.parse(end_time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

//        if (null != time && time.contains("startTime")) {
//            Map<String, String> tempMap = new HashMap<String, String>();
//            for (String str : time.split("_T_")) {
//                if (str.split("!").length > 1) {
//                    tempMap.put(str.split("!")[0], str.split("!")[1]);
//                }
//            }
//            String sTime = tempMap.get("startTime");
//            String eTime = tempMap.get("endTime");
//            if (null != sTime && !"".equals(sTime)) {
//                try {
//                    startTime = DATE_FAMAT.parse(sTime).getTime() / 1000L;
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//            }
//            if (null != eTime && !"".equals(eTime)) {
//                try {
//                    endTime = DATE_FAMAT.parse(eTime).getTime() / 1000L;
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//            }
//        }

        String[] pvids = p_ids;
        if (null != pvids && pvids.length > 0) {
            Integer[] ids = new Integer[pvids.length];
            for (int i = 0; i < pvids.length; i++) {
                try {
                    ids[i] = Integer.parseInt(pvids[i]);
                } catch (NumberFormatException e) {
                    ids[i] = 0;
                }
            }
            
            // returnList = iptvQualityService.getIptvQualityByIdsAndTime(ids,
            // startTime, endTime);

            qualityRateBeanList = iptvQualityService
                    .getIptvQualityBeanByIdsAndTime(ids,
                            start.getTime() / 1000, end.getTime() / 1000,
                            statunitsec);
            
            if (null!=qualityRateBeanList && !qualityRateBeanList.isEmpty()){
                logger.info("query QualityRateBeanList size   ["
                        + qualityRateBeanList.size() + "]");                
            }

        }

        // for(Object[] iptvLostRate : returnList){
        // String rate = getRate((Long)iptvLostRate[2], (Long)iptvLostRate[3]);
        // String date = getDate((Long)iptvLostRate[4]);
        // if(returnMap.containsKey(iptvLostRate[0]+"_"+iptvLostRate[1])){
        // returnMap.get(iptvLostRate[0]+"_"+iptvLostRate[1]).add(rate);
        // returnDateMap.get(iptvLostRate[0]+"_"+iptvLostRate[1]).add(date);
        // }else{
        // List<String> tempList = new ArrayList<String>();
        // List<String> tempDateList = new ArrayList<String>();
        // tempList.add(rate);
        // tempDateList.add(date);
        // returnMap.put(iptvLostRate[0]+"_"+iptvLostRate[1], tempList);
        // returnDateMap.put(iptvLostRate[0]+"_"+iptvLostRate[1], tempDateList);
        // }
        // }

        for (IptvQualityRateBean qualityBean : qualityRateBeanList) {
            logger.info("quality size  : " + qualityBean.getDataList().size());
            for (PictureData data : qualityBean.getDataList()) {
                String date = getDate(data.getTime());
                if (returnMap.containsKey(qualityBean.getIdRobot() + "_"
                        + qualityBean.getName())) {
                    returnMap.get(
                            qualityBean.getIdRobot() + "_"
                                    + qualityBean.getName()).add(
                            getRate(data.getRate()));
                    returnDateMap.get(
                            qualityBean.getIdRobot() + "_"
                                    + qualityBean.getName()).add(date);
                } else {
                    List<String> tempList = new ArrayList<String>();
                    List<String> tempDateList = new ArrayList<String>();
                    tempList.add(String.valueOf(data.getRate()));
                    tempDateList.add(date);
                    returnMap.put(qualityBean.getIdRobot() + "_"
                            + qualityBean.getName(), tempList);

                    returnDateMap.put(qualityBean.getIdRobot() + "_"
                            + qualityBean.getName(), tempDateList);
                }

            }

        }

        OFCGraph graphData = new OFCGraph();
        String tempKey = "";
        // 循环输出多条曲线
        for (String key : returnMap.keySet()) {
            tempKey = key;
            graphData.set_data(returnMap.get(key));
            String color = randomColor();
            if (randomColorList.size() > 0) {
                while (randomColorList.contains(color)) {
                    color = randomColor();
                }
            }
            graphData.area_hollow("2", "0", "25", color,
                    key.split("_").length > 1 ? key.split("_")[1] : "", "12",
                    color);
        }
        graphData.set_x_labels(returnDateMap.get(tempKey));
        int xSteps = returnDateMap.get(tempKey).size() / 24;
        graphData.set_x_offset(false);
        graphData.set_y_max(this.maxNum);
        graphData.set_y_min(99);

        graphData.set_x_axis_steps(xSteps);
        graphData.set_x_label_style("10", "#000000", 0, xSteps * 5, "");

        graphData.set_y_legend("%", 13, "#C11B01");
        return graphData;
    }

    /**
     * 计算出比例，显示Y坐标用
     * @param errorCount
     * @param tatolCount
     * @return String
     */
    public String getRate(Long errorCount, Long tatolCount) {
        Double rate = (tatolCount.doubleValue() - errorCount.doubleValue())
                / tatolCount.doubleValue() * 100.0;
        if (rate > this.maxNum) {
            this.maxNum = rate.intValue() + 1;
        }
        return "" + rate;
    }

    /**
     * 计算出比例，显示Y坐标用
     * @param dataVal
     * @return String
     */
    public String getRate(Double dataVal) {
        if (dataVal > this.maxNum) {
            this.maxNum = dataVal.intValue() + 1;
        }        
        return "" + dataVal;
    }

    /**
     * 将Long类型转换成Date类，显示x坐标用
     * @param logTime
     * @return
     */
    public String getDate(Long logTime) {
        return DATE_FAMAT.format(new Date(logTime * 1000L));
    }

    /**
     * 将Long类型转换成Date类，显示x坐标用
     * @param logTime
     * @return
     */
    public String getDate(String logTime) {
        Date time = null;
        try {
            time = INPUT_FAMAT.parse(logTime);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (null != time) {
            return DATE_FAMAT.format(time);
        } else {
            return "";
        }
    }

    /**
     * 随机色
     * @return color
     */
    public String randomColor() {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        sb.append("#");
        for (int i = 0; i < 6; i++) {
            int temp = random.nextInt(16);
            if (temp >= 10) {
                switch (temp) {
                case 10:
                    sb.append("A");
                    break;
                case 11:
                    sb.append("B");
                    break;
                case 12:
                    sb.append("C");
                    break;
                case 13:
                    sb.append("D");
                    break;
                case 14:
                    sb.append("E");
                    break;
                default:
                    sb.append("F");
                    break;
                }
            } else {
                sb.append(temp);
            }
        }
        return sb.toString();
    }
}
